package datastructure.segmenttree;

/**
 * @author: Oliver
 * @time: 2020/5/29/9:30
 */
public class SegmentTree<E> {
    //存放数据副本
    private E[] data;
    //构造成线段树，线段树需要的大小  推导出来为 4* arr.length
    private E[] tree;
    private Merger<E> merger;

    public SegmentTree(E[] arr, Merger<E> merger) {
        this.merger = merger;
//        进行初始化, 将一个数组初始化成一个线段树结构
        this.data = (E[]) new Object[arr.length];
        for (int i = 0; i < arr.length; i++) {
            data[i] = arr[i];
        }

        //初始化线段树数组容量，以最大值方式进行初始化，开辟空间为4* arr.length
        this.tree = (E[]) new Object[4 * arr.length];
        buildSegmentTree(0, 0, arr.length - 1);
    }

    //在treeIndex的位置创建表示区间[l...r]的线段树
    private void buildSegmentTree(int treeIndex, int l, int r) {
        if (l == r) {
            tree[treeIndex] = data[l];
            return;
        }
        //如果区间不是最小区间，就继续向下拆分
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        //中间值,防止两个整数相加超过整数上界
        int mid = l + (r - l) / 2;
        buildSegmentTree(leftTreeIndex, l, mid);
        buildSegmentTree(rightTreeIndex, mid + 1, r);
        tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
    }

    public int getSize() {
        return data.length;
    }

    public E get(int index) {
        if (index < 0 || index >= data.length)
            throw new IllegalArgumentException("Index is illegal.");
        return data[index];
    }

    //返回完全二叉树数组表示中，一个索引所表示的元素的左孩子索引位置
    private int leftChild(int index) {
        return 2 * index + 1;
    }

    //返回完全二叉树数组表示中，一个索引所表示的元素的右孩子索引位置
    private int rightChild(int index) {
        return 2 * index + 2;
    }

    // 返回区间[queryL, queryR]的值
    public E query(int queryL, int queryR) {
        //合理性校验
        if (queryL < 0 || queryL >= data.length ||
                queryR < 0 || queryR >= data.length || queryL > queryR)
            throw new IllegalArgumentException("Index is illegal.");
        return query(0, 0, data.length - 1, queryL, queryR);
    }

    // 在以treeIndex为根的线段树中[l...r]的范围里，搜索区间[queryL...queryR]的值
    private E query(int treeIndex, int l, int r, int queryL, int queryR) {
        //递归到底的情况
        if (l == queryL && r == queryR) {
            return tree[treeIndex];
        }

        //如果区间不是最小区间，就继续向下拆分
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        // 进行递归查询
        int mid = l + (r - l) / 2;
        if (queryL >= mid + 1) {
            return query(rightTreeIndex, mid + 1, r, queryL, queryR);
        } else if (queryR <= mid) {
            return query(leftTreeIndex, l, mid, queryL, queryR);
        }
        //特殊情况  --需要查询区间为两个两个区间的一部分 [2,5] 在 [2,3] + [4,5],也就是说将查询区间一分为二
        E leftRes = query(leftTreeIndex, l, mid, queryL, mid);
        E rightRes = query(rightTreeIndex, mid + 1, r, mid + 1, queryR);
        return merger.merge(leftRes, rightRes);
    }

    public void set(int index, E e) {
        set(0, 0, data.length - 1, index, e);
    }

    private void set(int treeIndex, int l, int r, int index, E e) {
        if (l == r) {
            tree[treeIndex] = e;
            return;
        }
        //如果区间不是最小区间，就继续向下拆分
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        // 进行递归查询
        int mid = l + (r - l) / 2;
        if (index >= mid + 1) {
            set(rightTreeIndex, mid + 1, r, index, e);
        } else {//index<=mid
            set(leftTreeIndex, l, mid, index, e);
        }
        //更新节点值
        tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);

    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (int i = 0; i < tree.length; i++) {
            if (tree[i] != null) {
                sb.append(tree[i]);
            } else {
                sb.append("null");
            }
            if (i != tree.length - 1)
                sb.append(", ");
        }
        return sb.append("]").toString();
    }
}
